import datetime

from django.core.paginator import Paginator
from django.http import HttpResponseRedirect, HttpResponse, HttpResponseForbidden, JsonResponse
from django.shortcuts import render
from user.models import User
from .models import *
from django.db.models import Count


def login(req):
    """
    跳转登录
    :param req:
    :return:
    """
    return render(req, 'login.html')


def register(req):
    """
    跳转注册
    :param req:
    :return:
    """
    return render(req, 'register.html')

def index(request):
    role = request.session['role']
    
    username = request.session['username']
    idnumber = request.session['idnumber']

    total_user = len(User.objects.all())
    date = datetime.datetime.today()
    month = date.month
    year = date.year
    
    ## 高风险城市 高风险人数  
    h_person_num = HesuanList.objects.filter(hesuan_result=2).all().count()
   
    #登记人数
    person_num_total = HesuanList.objects.all().count()    
    #登记人数
    jigou_num_total = User.objects.filter(role=2).all().count()     
    return render(request,'index.html',locals())



def index2(req):
    """
    跳转首页
    :param req:
    :return:
    """
    username = req.session['username']
    total_user = len(User.objects.all())
    date = datetime.datetime.today()
    month = date.month
    year = date.year
    result = TotalInfo.objects.all().order_by('-id')[0]
    total_confirm = result.confirm
    total_heal = result.heal
    total_dead = result.dead
    total_nowConfirm = result.nowConfirm
    total_noInfect = result.noInfect
    total_import = result.import_count

    # predict(req)
    county_total = CountyTotal.objects.all()
    county_total_list = []
    for i in county_total:
        county_total_list.append({
            'name': i.name,
            'value': i.confirm
        })
    qg_list = []
    qg_count_list = []
    r1 = CountyTotal.objects.all().order_by('-confirm')[0:10]
    for i in r1:
        qg_list.append(i.name)
        qg_count_list.append(i.confirm)
    r2 = CountyTotal.objects.all().order_by('-importedCase')[0:5]
    jwsr = []
    for j in r2:
        jwsr.append({
            'name':j.name,
            'value':j.importedCase
        })
    r3 = ChinaDayList.objects.all()
    result1 = []
    result2 = []
    result3 = []
    result4 = []
    for m in r3:
        result1.append(m.append_time)
        result2.append(m.heal)
        result3.append(m.dead)
        result4.append(m.confirm)
    r4 = ChinaDayAddList.objects.all()
    result5 = []
    result6 = []
    result7 = []
    result8 = []
    for m in r4:
        result5.append(m.append_time)
        result6.append(m.confirm)
        result7.append(m.suspect)
        result8.append(m.importedCase)
    return render(req, 'index2.html', locals())


def login_out(req):
    """
    注销登录
    :param req:
    :return:
    """
    del req.session['username']
    return HttpResponseRedirect('/')





def predict(request):
    from .crawer import get_data, get_info
    data = get_info()
    diseaseh5Shelf = data['diseaseh5Shelf']
    TotalInfo.objects.create(
        confirm=diseaseh5Shelf['chinaTotal']['confirm'],
        heal=diseaseh5Shelf['chinaTotal']['heal'],
        dead=diseaseh5Shelf['chinaTotal']['dead'],
        nowConfirm=diseaseh5Shelf['chinaTotal']['nowConfirm'],
        noInfect=diseaseh5Shelf['chinaTotal']['noInfect'],
        import_count=diseaseh5Shelf['chinaTotal']['importedCase'],
    )
    leiji = diseaseh5Shelf['areaTree'][0]['children']
    for i in leiji:
        CountyTotal.objects.filter(name=i['name']).update(
            confirm=i['total']['confirm'],
        )
    for j in leiji:
        for m in j['children']:
            if m['name'] == '境外输入':
                CountyTotal.objects.filter(name=j['name']).update(
                    importedCase=m['total']['confirm']
                )

    data2 = get_data()
    china_day_list = data2['chinaDayList']
    for i in china_day_list:
        r = ChinaDayList.objects.filter(append_time=i['date']).first()
        if not r:
            ChinaDayList.objects.create(
                heal=i['heal'],
                dead=i['dead'],
                confirm=i['confirm'],
                append_time=i['date']
            )

    china_day_add_list = data2['chinaDayAddList']
    for i in china_day_add_list:
        r = ChinaDayAddList.objects.filter(append_time=i['date']).first()
        if not r:
            ChinaDayAddList.objects.create(
                suspect=i['suspect'],
                importedCase=i['importedCase'],
                confirm=i['confirm'],
                append_time=i['date']
            )

    return JsonResponse({'msg': 'ok'})


def get_database(request):
    """
    获取用户列表信息 | 模糊查询
    :param request:
    :return:
    """
    keyword = request.GET.get('name')
    page = request.GET.get("page", '')
    limit = request.GET.get("limit", '')
    role_id = request.GET.get('position', '')
    response_data = {}
    response_data['code'] = 0
    response_data['msg'] = ''
    data = []
    if keyword is None:
        results_obj = CountyTotal.objects.all()
    else:
        results_obj = CountyTotal.objects.filter(name__contains=keyword).all()
    paginator = Paginator(results_obj, limit)
    results = paginator.page(page)
    if results:
        for result in results:
            record = {
                "id": result.id,
                "name": result.name,
                "confirm": result.confirm,
                "importedCase": result.importedCase,
            }
            data.append(record)
        response_data['count'] = len(results_obj)
        response_data['data'] = data

    return JsonResponse(response_data)

def database_info(request):
    """
    跳转用户页面
    """
    username = request.session['username']
    role = int(request.session['role'])
    user_id = request.session['user_id']
    return render(request, 'database_info.html', locals())

def dengji(request):
    """
    跳转用户页面
    """
    username = request.session['username']
    role = int(request.session['role'])
    user_id = request.session['user_id']
    user = User.objects.filter(id=user_id)
    names = user[0].names

    yangxing_count = HesuanList.objects.filter(hesuan_result=2).filter(status=1).count()
    total_count = HesuanList.objects.filter(status=1).count()

    user_jg = User.objects.filter(role=2).order_by("id").all()
    return render(request, 'dengji.html', locals())

def getdengji(request):
    """
    跳转用户页面
    """
    role=int(request.session['role'])
    idnumber = request.session['idnumber']
    juserid = request.session['user_id']
    keyword = request.GET.get('name')
    grade = request.GET.get('hesuan_result','0')
    page = request.GET.get("page", 1)
    limit = request.GET.get("limit", 20)
    response_data = {}
    response_data['code'] = 0
    response_data['msg'] = ''
    data = []

    results_obj = HesuanList.objects.order_by("id").all()
    if keyword :
        results_obj = results_obj.filter(jpersonmobile=keyword)
    if grade !='0' :
        results_obj = results_obj.filter(hesuan_result=grade)

    if role ==2 :
        results_obj = results_obj.filter(jidnumer=idnumber)
    if role ==3 :
        results_obj = results_obj.filter(juserid=juserid)


    paginator = Paginator(results_obj, limit)
    results = paginator.page(page)

    if results:
        for result in results:
            status=''
            if result.status==1:
                    status='<font color="yellow">上报结果</font>'
            elif result.status==3:
                    status='<font color="grey">已取消</font>'
            elif result.status==4:
                    status='<font color="blue">已审核</font>'
            else:
                status='未审核'

            if result.hesuan_result == '2':
                    grade='<font color="red">阳性</font>'
            elif result.hesuan_result=='1':
                    grade='阴性'
            else:
                 grade='未检测'



            if result.hesuan_yangben == '1':
                    yb='<font color="red">鼻咽拭子</font>'
            elif result.hesuan_yangben=='2':
                    yb='口咽拭子'
            elif result.hesuan_yangben=='3':
                    yb='痰液'
            else:
                 yb='其他'

            record = {
                "id": result.id,
                "area": result.area,
                #"title": grade,
                "juserid":juserid,
                "jtime": result.jtime,
                "jpersonname": result.jpersonname,
                "jcontent": result.jcontent,
                "jpersonmobile": result.jpersonmobile,
                "jidnumer": result.jidnumer,
                "hesuan_result": grade,
                "hesuan_result_uptime": result.hesuan_result_uptime,
                "hesuan_yangben":yb,
                "hesuan_jigou": result.hesuan_jigou,
                "status":status
            }

            data.append(record)
        response_data['count'] = len(results_obj)
        response_data['data'] = data
    
    
    return JsonResponse(response_data)
   
def adddengji(request):
    """
    注册账号
    :return:
    """
    try:
        title = request.POST.get('title')
        area = request.POST.get('area')
        jtime = request.POST.get('jtime')
        jpersonname = request.POST.get('jpersonname')
        jcontent = request.POST.get('jcontent')
        jpersonmobile = request.POST.get('jpersonmobile')
        jidnumer = request.POST.get('jidnumer')
        juserid =  request.session['user_id']

        HesuanList.objects.create(
            title=title,
            area=area,
            jtime=jtime,
            jpersonname=jpersonname,
            jpersonmobile=jpersonmobile,
            jcontent=jcontent,
            jidnumer=jidnumer,
             juserid=juserid,
             status=0
        )
        response_data = {'message': '登记成功'}
        return JsonResponse(response_data)
    except Exception as e:
        print(e)
        return JsonResponse({'message': '登记失败'}, status=401)


def dengjicheck(request):
    """
    """
    response_data = {}
    user_id = request.POST.get('hid')
    hesuan_yangben = request.POST.get('hesuan_yangben')
    hesuan_result_uptime = request.POST.get('hesuan_result_uptime')
    hesuan_jigou = request.POST.get('hesuan_jigou')
    hesuan_result = request.POST.get('hesuan_result')
    status = request.POST.get('status')
    

    HesuanList.objects.filter(id=user_id).update(
        hesuan_yangben=hesuan_yangben,
        hesuan_result_uptime=hesuan_result_uptime,
        hesuan_jigou=hesuan_jigou,
        hesuan_result=hesuan_result,
        status=status,
        )
    response_data['msg'] = 'success'
    return JsonResponse(response_data, status=201)


#取消
def delhesuanlist(request):
    """
    跳转用户页面
    """
    id = request.POST.get('id')
    result = HesuanList.objects.filter(id=id).first()
    user_id = request.session['user_id']

    
    if  result.status==0:
          HesuanList.objects.filter(id=id).update(
                status=3,
            )
          response_data = {'message': '操作成功！'}
          return JsonResponse(response_data, status=201)
    else:
          response_data = {'message': '该申请已经在处理中，无法取消'} 
          return JsonResponse(response_data, status=201)

def personsearch(request):
    """
    跳转用户页面
    """
    username = request.session['username']
    role = int(request.session['role'])
    user_id = request.session['user_id']
    return render(request, 'notice.html', locals())

#地区统计  #风险统计
def get_database(request):
    """
    获取用户列表信息 | 模糊查询
    :param request:
    :return:
    """
    username = request.session['username']
    role = int(request.session['role'])
    user_id = request.session['user_id']

 
    results_obj1 = HesuanList.objects.values("hesuan_result_uptime").annotate(count=Count("id")).all()     
    results_obj_time = list(results_obj1)

    results_obj3 = HesuanList.objects.values("hesuan_result_uptime").annotate(count=Count("id")).filter(hesuan_result=1).all()     
    results_obj_time_yangxing = list(results_obj3)
    

    results_obj2 = HesuanList.objects.values("hesuan_result").annotate(count=Count("id")).all()     
    results_obj_result = list(results_obj2)

    # results_obj_fx1 = HesuanList.objects.values("title").annotate(count=Count("id")).all()     
    # results_obj_fx = list(results_obj_fx1)
    #获取高风险的地区有
    # results_obj_h_c = HesuanList.objects.filter(result__gt=0).all()     
    # results = list(results_obj_h_c)

    # if results:
    #     for result in results:
    #         if result.hesuan_result=='2':
    #                 data_h.append(result.hesuan_jigou)
    #                 continue
    #         elif result.hesuan_result=='1':
    #              data_m.append(result.hesuan_jigou)
    #              continue
    return render(request, 'get_database.html', locals())

#feedback
def feedback(request):
    """
    跳转用户页面
    """
    username = request.session['username']
    role = int(request.session['role'])
    username = request.session['username']
    user_id = request.session['user_id']
    return render(request, 'feedback.html', locals())

#feedback
def addfeedbackhtml(request):
    """
    跳转用户页面
    """
    username = request.session['username']
    role = int(request.session['role'])
    username = request.session['username']
    return render(request, 'feedback_add.html', locals())

def getfeedback(request):
    """
    跳转用户页面
    """
    page = request.GET.get("page", 1)
    limit = request.GET.get("limit", 20)
    response_data = {}
    response_data['code'] = 0
    response_data['msg'] = ''
    data = []
    results_obj = Feedback.objects.order_by("id").all()
    paginator = Paginator(results_obj, limit)
    results = paginator.page(page)
    if results:
        for result in results:
            status=''
            
            if result.fstatus == 1:
                 status='<font color="blue">通过</font>'
            elif result.fstatus==2:
                 status='<font color="red">未通过</font>'
            else:
                 status='未审核'
            print(status)       
            record = {
                "id": result.id,
                "ftitle": result.ftitle,
                "ftime": result.ftime,
                "fuser": result.fuser,
                "fcontent": result.fcontent,
                "fstatus": status,
               
            }

            data.append(record)
        response_data['count'] = len(results_obj)
        response_data['data'] = data

    return JsonResponse(response_data)

def addfeedback(request):
    """
    注册账号
    :return:
    """
    try:
        now = datetime.datetime.now()

        ftitle = request.POST.get('ftitle')
        fcontent = request.POST.get('fcontent')
        fuser=request.session['username']
        ftime=now.strftime("%Y-%m-%d %H:%M:%S")
        fstatus='0'
        
        Feedback.objects.create(
            ftitle=ftitle,
            fcontent=fcontent,
            ftime=ftime,
            fuser=fuser,
            fstatus=fstatus
    
        )
        response_data = {'message': '反馈成功'}
        return JsonResponse(response_data)
    except Exception as e:
        print(e)
        return JsonResponse({'message': '反馈失败'}, status=401)

def delfeedback(request):
    """
    跳转用户页面
    """
    id = request.POST.get('id')
    result = Feedback.objects.filter(id=id).first()
    try:
        if not result:
            response_data = {'error': '删除失败！', 'message': '找不到id为%s' % id}
            return JsonResponse(response_data, status=403)
        result.delete()
        response_data = {'message': '删除成功！'}
        return JsonResponse(response_data, status=201)
    except Exception as e:
        response_data = {'message': '删除失败！'}
        return JsonResponse(response_data, status=403)
    return render(request, 'database_info.html', locals())

def chekfeedback(request):
    """
    """
    response_data = {}
    user_id = request.POST.get('id')
    fstatus = request.POST.get('status',1)
    Feedback.objects.filter(id=user_id).update(
        fstatus=fstatus,
        )
    response_data['msg'] = 'success'
    return JsonResponse(response_data, status=201)
